package com.xinggq.gateway.filter;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinggq.common.CommonResult;
import com.xinggq.common.constant.AuthConstants;
import com.xinggq.gateway.config.AuthProperties;
import com.xinggq.gateway.service.TokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 令牌验证过滤器
 * 验证请求中的访问令牌，并将用户信息传递给下游服务
 *
 * @author xinggq
 * @since 2023-10-20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenAuthFilter implements GlobalFilter, Ordered {

  private final TokenService tokenService;
  private final AuthProperties authProperties;
  private final ObjectMapper objectMapper;
  private final AntPathMatcher pathMatcher = new AntPathMatcher();



  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String path = request.getURI().getPath();

    // 检查是否是白名单路径，如果是则跳过验证
    if (isIgnoreUrl(path)) {
      return chain.filter(exchange);
    }

    // 获取请求头中的令牌
    String token = getToken(request);
    if (!StringUtils.hasText(token)) {
      return unauthorized(exchange, "缺少访问令牌");
    }

    // 验证令牌
    try {
      return tokenService.validateToken(token)
          .flatMap(userInfo -> {
            if (userInfo == null) {
              return unauthorized(exchange, "无效的访问令牌");
            }

            // 将用户信息添加到请求头中，传递给下游服务
            ServerHttpRequest newRequest = request.mutate()
                .header(AuthConstants.USER_ID_HEADER, String.valueOf(userInfo.getUserId()))
                .header(AuthConstants.USER_NAME_HEADER, userInfo.getUsername())
                .header(AuthConstants.TENANT_ID_HEADER,
                    userInfo.getTenantId() != null ? userInfo.getTenantId().toString() : "")
                .build();

            return chain.filter(exchange.mutate().request(newRequest).build());
          })
          .onErrorResume(e -> {
            log.error("令牌验证失败", e);
            return unauthorized(exchange, "令牌验证失败: " + e.getMessage());
          });
    } catch (Exception e) {
      log.error("令牌验证过程中发生异常", e);
      return unauthorized(exchange, "令牌验证失败");
    }
  }

  @Override
  public int getOrder() {
    // 确保在其他过滤器之前执行
    return -100;
  }

  /**
   * 检查请求路径是否在白名单中
   */
  private boolean isIgnoreUrl(String path) {
    List<String> ignoreUrls = authProperties.getIgnoreUrls();
    log.info("检查路径: {}, 白名单: {}", path, ignoreUrls);
    if (ignoreUrls != null) {
      for (String ignoreUrl : ignoreUrls) {
        if (pathMatcher.match(ignoreUrl, path)) {
          log.info("路径 {} 匹配白名单规则 {}", path, ignoreUrl);
          return true;
        }
      }
    }
    log.info("路径 {} 不在白名单中", path);
    return false;
  }

  /**
   * 从请求头中获取令牌
   */
  private String getToken(ServerHttpRequest request) {
    String token = request.getHeaders().getFirst(AuthConstants.HEADER_AUTHORIZATION);
    if (StringUtils.hasText(token) && token.startsWith(AuthConstants.BEARER_PREFIX)) {
      return token.substring(AuthConstants.BEARER_PREFIX.length());
    }
    return null;
  }

  /**
   * 返回未授权响应
   */
  private Mono<Void> unauthorized(ServerWebExchange exchange, String message) {
    ServerHttpResponse response = exchange.getResponse();
    response.setStatusCode(HttpStatus.UNAUTHORIZED);
    response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    CommonResult<Void> commonResult = CommonResult.authFail(message);
    byte[] bytes;
    try {
      bytes = objectMapper.writeValueAsBytes(commonResult);
    } catch (JsonProcessingException e) {
      bytes = "{\"code\":401,\"message\":\"未授权\"}".getBytes(StandardCharsets.UTF_8);
    }
    DataBuffer buffer = response.bufferFactory().wrap(bytes);
    return response.writeWith(Mono.just(buffer));
  }
}